package org.itboys.commons.utils.common;

import java.util.HashSet;
import java.util.Set;

import com.alibaba.fastjson.JSON;

public class ClassUtils {

    @SuppressWarnings({ "rawtypes" })
    private static final Set<Class> simpleClasses = new HashSet<Class>();

    static {
        simpleClasses.add(int.class);
        simpleClasses.add(Integer.class);
        simpleClasses.add(long.class);
        simpleClasses.add(Long.class);
        simpleClasses.add(Byte.class);
        simpleClasses.add(byte.class);
        simpleClasses.add(double.class);
        simpleClasses.add(Double.class);
        simpleClasses.add(boolean.class);
        simpleClasses.add(Boolean.class);
        simpleClasses.add(char.class);
        simpleClasses.add(Character.class);
        simpleClasses.add(Float.class);
        simpleClasses.add(float.class);
        simpleClasses.add(void.class);
        simpleClasses.add(String.class);
        simpleClasses.add(Short.class);
        simpleClasses.add(short.class);
    }

    @SuppressWarnings("rawtypes")
    public static boolean isSimpleType(Class clazz) {
        return simpleClasses.contains(clazz);
    }

    @SuppressWarnings("rawtypes")
    public static boolean isTreeClass(Class<?> childClazz, Class<?> parentClazz) {
        if (childClazz.equals(parentClazz)) {
            return true;
        }
        if (parentClazz.isInterface()) {
            Class<?>[] types = childClazz.getInterfaces();
            for (Class<?> type : types) {
                if (type.equals(parentClazz)) {
                    return true;
                }
            }
        }
        Class sc = childClazz.getSuperclass();
        while (sc != null) {
            if (sc.equals(parentClazz)) {
                return true;
            }
            sc = sc.getSuperclass();
        }
        return false;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Object convert(String json, Class type) {
        if (json == null || type == void.class) {
            return null;
        }
        if (type == Boolean.class || type == boolean.class) {
            return Boolean.parseBoolean(json);
        } else if (type == int.class || type == Integer.class) {
            return Integer.parseInt(json);
        } else if (type == long.class || type == Long.class) {
            return Long.parseLong(json);
        } else if (type == float.class || type == Float.class) {
            return Float.parseFloat(json);
        } else if (type == String.class) {
            return json;
        } else if (type == Byte.class || type == byte.class) {
            return Byte.parseByte(json);
        } else if (type == Double.class || type == double.class) {
            return Double.parseDouble(json);
        } else if (type == char.class || type == Character.class) {
            return json.toCharArray()[0];
        }
        return JSON.parseObject(json, type);
    }
}
